<template>
  <div class="container">
    <div class="navbar-container">
      <nav class="navbar">
        <ul>
          <li><router-link to="/"><i class="fas fa-home"></i> 首页</router-link></li>
          <li>
            <router-link :to="{ name: 'OneselfCenter', query: { tab: 'favorites' }}">
              <i class="fas fa-heart"></i> 收藏
            </router-link>
          </li>
          <li><router-link to="/profile"><i class="fas fa-user"></i> 个人中心</router-link></li>
        </ul>
        <div class="search-section">
          <i class="fas fa-search"></i>
          <input
              type="text"
              placeholder="搜索内容..."
              class="search-input"
              v-model="searchQuery"
          />
        </div>
      </nav>
    </div>

    <div class="topic-container">
      <div class="topic-header">
        <h2>社区话题</h2>
        <div class="topic-buttons">
          <button class="btn" @click="sortTopicsByTime">最新发布</button>
          <button class="btn btn-primary" @click="showTopicModal = true">发布话题</button>
        </div>
      </div>
      <div class="topic-list">
        <div
            class="topic-item"
            v-for="topic in filteredTopics"
            :key="topic.id"
            @click="goToTopicDetail(topic.id)"
        >
          <div class="topic-avatar">
            <img :src="topic.authorAvatar" alt="avatar" />
          </div>
          <div class="topic-content">
            <div class="topic-info">
              <h3>{{ topic.title }}</h3>
              <p class="author-time">
                <span>{{ topic.author }}</span>
                <span>{{ formatTime(topic.timeAgo) }}</span>
              </p>
            </div>
            <p class="description">{{ topic.description }}</p>
            <div class="topic-actions">
              <button class="btn-action"><i class="fas fa-thumbs-up"></i> {{ topic.likes }}</button>
              <button class="btn-action"><i class="fas fa-comment"></i> {{ topic.commentCount }}</button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <el-dialog v-model="showTopicModal" title="发布话题" width="500px">
      <el-form :model="newTopic" label-width="80px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="newTopic.title" />
        </el-form-item>
        <el-form-item label="内容" prop="description">
          <el-input v-model="newTopic.description" type="textarea" rows="5" />
        </el-form-item>
        <el-form-item label="图片">
          <el-upload
              action="#"
              list-type="picture-card"
              :auto-upload="false"
              :on-change="handleImageUpload"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="视频">
          <el-upload
              action="#"
              :auto-upload="false"
              :on-change="handleVideoUpload"
          >
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showTopicModal = false">取消</el-button>
        <el-button type="primary" @click="submitTopic">发布</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useCounterStore } from '@/stores/counter'
const counterStore = useCounterStore()

interface Topic {
  id: number
  title: string
  author: string
  authorAvatar: string
  timeAgo: string
  description: string
  likes: number
  commentCount: number
  image?: string | null
  video?: string | null
}

const router = useRouter()
const topics = ref<Topic[]>([])
const searchQuery = ref('')
const showTopicModal = ref(false)
const newTopic = ref({
  title: '',
  description: '',
  image: null as File | null,
  video: null as File | null
})

const filteredTopics = computed(() => {
  if (!searchQuery.value) return topics.value
  return topics.value.filter(topic =>
      topic.title.toLowerCase().includes(searchQuery.value.toLowerCase()))
})

onMounted(async () => {
  try {
    topics.value = await counterStore.getTopics()
  } catch (error) {
    ElMessage.error('加载话题失败')
  }
})

const formatTime = (timeAgo: string) => timeAgo

const goToTopicDetail = (id: number) => {
  router.push({ name: 'PostDetail', params: { id } })
}

const sortTopicsByTime = () => {
  topics.value.sort((a, b) => {
    const dateA = new Date(a.timeAgo.replace(/\./g, '-'))
    const dateB = new Date(b.timeAgo.replace(/\./g, '-'))
    return dateB.getTime() - dateA.getTime()
  })
}

const handleImageUpload = (file: File) => {
  newTopic.value.image = file.raw
}

const handleVideoUpload = (file: File) => {
  newTopic.value.video = file.raw
}

const submitTopic = async () => {
  if (!newTopic.value.title.trim()) {
    ElMessage.error('请输入标题')
    return
  }

  try {
    const createdTopic = await counterStore.createTopic({
      title: newTopic.value.title,
      description: newTopic.value.description,
      image: newTopic.value.image,
      video: newTopic.value.video
    })

    topics.value.unshift(createdTopic)
    showTopicModal.value = false
    newTopic.value = { title: '', description: '', image: null, video: null }
    ElMessage.success('话题发布成功')
  } catch (error) {
    ElMessage.error('发布话题失败')
  }
}
</script>

<style scoped>
.container {
  padding: 20px;
}

.navbar-container {
  background-color: white;
  padding: 10px;
  margin-bottom: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.navbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.navbar ul {
  list-style: none;
  display: flex;
  gap: 15px;
  margin: 0;
  padding: 0;
}

.navbar li {
  margin: 0;
}

.navbar a {
  text-decoration: none;
  color: #333;
  display: flex;
  align-items: center;
  gap: 5px;
}

.search-section {
  display: flex;
  align-items: center;
  gap: 10px;
}

.search-input {
  width: 250px;
  padding: 8px;
  border: 1px solid #ccc;
  border-radius: 4px;
}

.topic-container {
  background-color: #f9f9f9;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.topic-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.topic-buttons {
  display: flex;
  gap: 10px;
}

.btn {
  padding: 8px 16px;
  border: 1px solid #ccc;
  border-radius: 4px;
  background-color: white;
  cursor: pointer;
}

.btn-primary {
  background-color: #42b983;
  color: white;
  border: none;
}

.topic-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
  overflow-y: auto;
  max-height: 600px;
}

.topic-item {
  background-color: white;
  border-radius: 4px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  padding: 15px;
  display: flex;
  gap: 15px;
  cursor: pointer;
  transition: box-shadow 0.3s ease;
}

.topic-item:hover {
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.2);
}

.topic-avatar img {
  width: 40px;
  height: 40px;
  border-radius: 50%;
}

.topic-content {
  flex: 1;
}

.topic-info h3 {
  margin: 0 0 10px;
}

.author-time {
  display: flex;
  justify-content: space-between;
  font-size: 0.9em;
  color: #666;
}

.description {
  margin: 10px 0 0;
}

.topic-actions {
  display: flex;
  gap: 10px;
  margin-top: 10px;
}

.btn-action {
  display: flex;
  align-items: center;
  gap: 5px;
  background: none;
  border: none;
  cursor: pointer;
  color: #666;
}

.btn-action:hover {
  color: #42b983;
}
</style>